package test.design_pattern.strategy;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class SaleService {

    private HashMap<String,UserStrategy> userStrategyHashMap = new HashMap<>();

    private TestConstructorParam t ;

    /**
     *
     * spring容器初始化SaleService的时候，会调用这个构造函数，并且会给strategyList赋值！
     * 为什么呢，因为这个构造函数现在是SaleService的默认构造函数（因为没有SaleService（）），
     * 而spring容器为了能够实例化SaleService，会从已经注册的bean中，找到SaleService的构造函数需要的参数
     *
     * 问题：
     * 1.如果SaleService再加上另一个带参数的构造函数，spring会如何处理？
     * --- spring会不知道调用哪个构造函数而初始化失败，报错：
     *  No default constructor found; nested exception is java.lang.NoSuchMethodException: test.design_pattern.strategy.SaleService.<init>()
     *
     * 2.如果如果SaleService的构造函数不是list，而是单个UserStrategy，spring会如何处理？
     * --- spring会不知道给构造函数传哪个Component而初始化失败，报错：
     *  No qualifying bean of type 'test.design_pattern.strategy.UserStrategy' available: expected single matching bean but found 2:
     *  normalUserStrategy,vipUserStrategy
     * 	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:733)
     *  解决办法：在参数上加 @Qualifier("xxx") 告诉spring需要注入哪个bean
     *
     * @param strategyList
     */
    public SaleService(List<UserStrategy> strategyList){
        for (UserStrategy userStrategy : strategyList) {
            userStrategyHashMap.put(userStrategy.getUserType(),userStrategy);
        }
    }

//    public SaleService(@Qualifier("normalUserStrategy") UserStrategy strategy){
//        System.out.println(strategy.getUserType());
//    }

//    public SaleService(TestConstructorParam param){
//        this.t = param ;
//        System.out.println(t.getAaa());
//    }

    public double sale(String userType,double fee){
        UserStrategy userStrategy = userStrategyHashMap.get(userType);
        return userStrategy.compute(fee);
    }
}
